/*
 * 线程属性-创建脱离线程
 * 主线程不等待子线程结束,只通过thread_finished标志来检测子线程是否已结束,并显示线程之间仍然共享的变量.
 */
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <pthread.h>

void *thread_function(void *arg);

char g_message[] = "Hello World!";
int g_thread_finished = 0;

int main(){
    int res;
    pthread_t a_thread;
    pthread_attr_t thread_attr;

    res = pthread_attr_init(&thread_attr);
    if(res != 0){
        perror("Attribute creation failed");
        exit(EXIT_FAILURE);
    }

    res = pthread_attr_setdetachstate(&thread_attr, PTHREAD_CREATE_DETACHED);
    if(res != 0){
        perror("Setting detached attribute failed");
        exit(EXIT_FAILURE);
    }

    res = pthread_create(&a_thread, &thread_attr,
            thread_function, (void *)g_message);
    if(res != 0){
        perror("Thread creation failed");
        exit(EXIT_FAILURE);
    }

    (void)pthread_attr_destroy(&thread_attr);
    while(!g_thread_finished){
        printf("Waiting for thread to say it's finished\n");
        sleep(1);
    }
    printf("Other thread finished, bye!\n");
    exit(EXIT_SUCCESS);
}

void *thread_function(void *arg){
    printf("thread_function is running. Argument was %s\n", (char *)arg);
    sleep(4);
    printf("Second thread setting finished flag, and exit now\n");
    g_thread_finished = 1;
    pthread_exit(NULL);
}
